from celery import task
from saltcore.salt_core import *
from minions.models import Minions_status
from returner.models import *
from dashboard.models import *
import logging
import time
from cmdb.utils import *

logger = logging.getLogger('django')


@task()
def dashboard_task():
    # minion status data save to mysql
    sapi = SaltAPI()
    status = sapi.runner_status('status')
    key_status = sapi.list_all_key()
    up = len(status['up'])
    down = len(status['down'])
    accepted = len(key_status['minions'])
    unaccepted = len(key_status['minions_pre'])
    rejected = len(key_status['minions_rejected'])
    dashboard_status = Dashboard_status()
    try:
        Dashboard_status.objects.get(id=1)
    except:
        dashboard_status.id = 1
        dashboard_status.up = up
        dashboard_status.down = down
        dashboard_status.accepted = accepted
        dashboard_status.unaccepted = unaccepted
        dashboard_status.rejected = rejected
        dashboard_status.save()
    Dashboard_status.objects.filter(id=1).update(id=1, up=up, down=down, accepted=accepted, unaccepted=unaccepted, rejected=rejected)

@task()
def grains_task():
    # grains data save to mysql
    sapi = SaltAPI()
    status = sapi.runner_status('status')
    status_up = status['up']
    for host_name in status_up:
        grains = sapi.remote_noarg_execution(host_name, 'grains.items')
        try:
            Salt_grains.objects.get(minion_id=host_name)
        except:
            salt_grains = Salt_grains()
            salt_grains.grains = grains
            salt_grains.minion_id = host_name
            salt_grains.save()
        Salt_grains.objects.filter(minion_id=host_name).update(grains=grains, minion_id=host_name)
        print "Update " + host_name + " grains"
    '''
    # minion status , version data save to mysql
    for host_name in status_up:
        salt_grains = Salt_grains.objects.filter(minion_id=host_name)
        version = eval(salt_grains[0].grains).get('saltversion').decode('string-escape')
        try:
            Minions_status.objects.get(minion_id=host_name)
        except:
            minions_status.minion_id = host_name
            minions_status.minion_version = version
            minions_status.minion_status = 'Up'
            minions_status.save()
        Minions_status.objects.filter(minion_id=host_name).update(minion_id=host_name, minion_version=version, minion_status='Up')
    for host_name in status_down:
        try:
            Minions_status.objects.get(minion_id=host_name)
        except:
            minions_status.minion_id = host_name
            minions_status.minion_version = version
            minions_status.minion_status = 'Down'
            minions_status.save()
        Minions_status.objects.filter(minion_id=host_name).update(minion_id=host_name, minion_version=version, minion_status='Down')
    '''


@task()
def minions_status_task():
    #minion status , version data save to mysql
    sapi = SaltAPI()
    status_all = sapi.runner_status('status')
    for host_name in status_all['up']:
        salt_grains = Salt_grains.objects.filter(minion_id=host_name)
        try:
            version = eval(salt_grains[0].grains).get('saltversion').decode('string-escape')
        except:
            version = 'NULL'
            logger.error("Don't get minion version")
        try:
            Minions_status.objects.get(minion_id=host_name)
        except:
            status = Minions_status()
            status.minion_id = host_name
            status.minion_version = version
            status.minion_status = 'Up'
            status.save()
        Minions_status.objects.filter(minion_id=host_name).update(minion_id=host_name, minion_version=version, minion_status='Up')
    for host_name in status_all['down']:
        salt_grains = Salt_grains.objects.filter(minion_id=host_name)
        try:
            version = eval(salt_grains[0].grains).get('saltversion').decode('string-escape')
        except:
            version = 'NULL'
            logger.error("Don't get minion version")
        try:
            Minions_status.objects.get(minion_id=host_name)
        except:
            status = Minions_status()
            status.minion_id = host_name
            status.minion_version = version
            status.minion_status = 'Down'
            status.save()
        Minions_status.objects.filter(minion_id=host_name).update(minion_id=host_name, minion_version=version, minion_status='Down')


@task()
def accept_grains_task(minion_id):
    # when accept key save grains to mysql
    time.sleep(10)
    sapi = SaltAPI()
    grains = sapi.remote_noarg_execution(minion_id, 'grains.items')
    salt_grains = Salt_grains()
    salt_grains.grains = grains
    salt_grains.minion_id = minion_id
    salt_grains.save()
    print "accept " + minion_id + " key"



def host_sync_create(minion_list):
    for item in minion_list:
        grains = Salt_grains.objects.filter(minion_id=item)
        host_hostname = eval(grains[0].grains).get('id').decode('string-escape')
        host_ip = eval(grains[0].grains).get('fqdn_ip4')[0].decode('string-escape')
        host_os = eval(grains[0].grains).get('os').decode('string-escape')
        host_osrelease = eval(grains[0].grains).get('osrelease').decode('string-escape')
        host_manufacturer = eval(grains[0].grains).get('manufacturer').decode('string-escape')
        host_kernel = eval(grains[0].grains).get('kernel').decode('string-escape')
        host_kernel_release = eval(grains[0].grains).get('kernelrelease').decode('string-escape')
        host_cpu_model = eval(grains[0].grains).get('cpu_model').decode('string-escape')
        host_num_cpus = eval(grains[0].grains).get('num_cpus')
        host_disks = eval(grains[0].grains).get('disks')
        host_disk_total = eval(grains[0].grains).get('disk')
        host_memory = eval(grains[0].grains).get('mem_total')
        host_uuid = eval(grains[0].grains).get('uuid').decode('string-escape')
        host_sn = eval(grains[0].grains).get('serialnumber').decode('string-escape')
        try:
            host = Host()
            host.vendor = host_manufacturer
            host.hostname = host_hostname      #s1-sit-admin-web01
            host.cpu_model = host_cpu_model
            host.ip = host_ip
            host.sn = host_sn
            host.memory = host_memory
            host.env = IpSource.objects.get(id=env_dispatch(host_ip))
            host.asset_type = Manufactory_dispatch(host_manufacturer)
            host.status = 1
            host.kernel = host_kernel_release   #Linux 3.10.1211
            host.kernel_release = host_os + host_osrelease    #CentOS 7.2.3.112.
            host.cpu_model = host_cpu_model
            host.cpu_num = host_num_cpus
            host.disk = host_disk_total
            host.disks = host_disks
            host.uuid = host_uuid
            host.os = host_kernel
            host.group_id = 1
            host.project_id = 1

            host.save()
        except Exception as e:
            print e


def host_sync_update(minion_list):
    for item in minion_list:
        grains = Salt_grains.objects.filter(minion_id=item)
        host_hostname = eval(grains[0].grains).get('id').decode('string-escape')
        host_ip = eval(grains[0].grains).get('fqdn_ip4')[0].decode('string-escape')
        host_os = eval(grains[0].grains).get('os').decode('string-escape')
        host_osrelease = eval(grains[0].grains).get('osrelease').decode('string-escape')
        host_manufacturer = eval(grains[0].grains).get('manufacturer').decode('string-escape')
        host_kernel = eval(grains[0].grains).get('kernel').decode('string-escape')
        host_kernel_release = eval(grains[0].grains).get('kernelrelease').decode('string-escape')
        host_cpu_model = eval(grains[0].grains).get('cpu_model').decode('string-escape')
        host_num_cpus = eval(grains[0].grains).get('num_cpus')
        host_disks = eval(grains[0].grains).get('disks')
        host_disk_total = eval(grains[0].grains).get('disk')
        host_memory = eval(grains[0].grains).get('mem_total')
        host_uuid = eval(grains[0].grains).get('uuid').decode('string-escape')
        host_sn = eval(grains[0].grains).get('serialnumber').decode('string-escape')
        host_env_id = env_dispatch(host_ip)
        host = Host.objects.filter(hostname=item)
        host_asset_type = Manufactory_dispatch(host_manufacturer)

        if host.values("uuid").first()['uuid'] == host_uuid:
            try:
                host.update(hostname=host_hostname,
                            vendor=host_manufacturer,
                            ip=host_ip,
                            sn=host_sn,
                            os=host_kernel,
                            memory=host_memory,
                            kernel=host_kernel_release,
                            kernel_release=host_os + host_osrelease,
                            asset_type=host_asset_type,
                            env_id=host_env_id,
                            cpu_model=host_cpu_model,
                            cpu_num=host_num_cpus,
                            disk=host_disk_total,
                            disks=host_disks,

                            )
            except Exception as e:
                 print e